package com.cskaoyan.market.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.cskaoyan.market.util.AdminResponseCode;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;

/**
 * @ClassName AuthenticateFilter
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/3/21 10:15
 * @Version V1.0
 **/
// @WebFilter("/*")
public class AuthenticateFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
        // 每当发送一次请求，便会经过一次该方法
        // 判断当前请求是否是需要认证的地址
        HttpServletRequest request = (HttpServletRequest)req;
        String requestURI = request.getRequestURI();
        // 如果访问的既不是登录也不是注销，那么我就需要认证，认证当前发送请求的用户是否登录
        // 如果登录，则正常访问；如果没有登录，则不予访问
        ServletContext servletContext = req.getServletContext();
        List<String> uris = (List<String>)servletContext.getAttribute("uris");
        // replaceURI是URI去掉应用名之后的部分，比如 /admin/auth/login去掉应用名ROOT，还是原样
        String replaceURI = requestURI.replace(request.getContextPath(), "");
        if (!uris.contains(replaceURI)) {
            HttpSession session = request.getSession();
            Object info = session.getAttribute("info");
            if (info == null) {
                // 没有登录
                resp.getWriter().println(JacksonUtil
                    .writeValueAsString(ResponseUtil.fail(AdminResponseCode.ADMIN_NOT_AUTHENTICATED, "当前接口仅允许登录后使用")));
                return;
            }
        }
        chain.doFilter(request, resp);
    }

    @Override
    public void destroy() {

    }
}